package org.example.rpc.core.socket.client;

import org.example.rpc.common.entity.RpcRequest;
import org.example.rpc.common.entity.RpcResponse;
import org.example.rpc.common.eunm.RpcError;
import org.example.rpc.common.eunm.RpcResponseCode;
import org.example.rpc.common.exception.RpcException;
import org.example.rpc.core.RpcClient;
import org.example.rpc.core.serializer.CommonSerializer;
import org.example.rpc.core.socket.util.ObjectReader;
import org.example.rpc.core.socket.util.ObjectWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.Socket;

public class SocketClient implements RpcClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(SocketClient.class);

    private final String host;

    private final int port;

    private CommonSerializer serializer;

    public SocketClient(String host, int port){
        this.host = host;
        this.port = port;
    }

    public Object sendRequest(RpcRequest request) {
        if(serializer == null){
            LOGGER.error("未设置序列化器");
            throw new RpcException(RpcError.SERIALIZER_NOT_FOUND);
        }
        try (Socket socket = new Socket(host, port)) {
            OutputStream outputStream = socket.getOutputStream();
            InputStream inputStream = socket.getInputStream();
            ObjectWriter.writeObject(outputStream, request, serializer);
            RpcResponse rpcResponse = (RpcResponse) ObjectReader.readObject(inputStream);
            if (rpcResponse == null) {
                LOGGER.error("服务调用失败，service：{}", request.getInterfaceName());
                throw new RpcException(RpcError.SERVICE_INVOCATION_FAILURE, " service" + request.getInterfaceName());
            }
            if(rpcResponse.getStatusCode() == null || rpcResponse.getStatusCode() != RpcResponseCode.SUCCCESS.getCode()){
                LOGGER.error("服务调用失败，service：{}, response:{}", request.getInterfaceName(),rpcResponse);
            }

            return rpcResponse.getData();
        } catch (IOException e) {
            LOGGER.error("请求异常", e);
            throw new RpcException("服务调用失败", e);
        }
    }

    @Override
    public void setSerializer(CommonSerializer serializer) {
        this.serializer = serializer;
    }
}
